1, the await object behind the command Promise , the result may be rejected , so it is better to put the await command in the try...catch code block.
2, await the asynchronous operation behind multiple commands, if there is no secondary relationship, it is best to let them trigger at the same time.
// notation a let [foo, bar] = await Promise.all ([Getfoo (), Getbar ()]); // notation Two let foopromise == = = await barpromise;
3, the await command can only be used in the async function, if used in ordinary functions, will be error.
function // There's no need for async . Let docs = [{}, {}, {}]; // may get incorrect results function (DOC) { await db.post (DOC); });
The above code may not work properly, because at this point three operations will be executed concurrently, that is db.post , execution at the same time, not secondary execution. The correct notation is to use for loops.
function DBFUC (db) { = [{}, {}, {}]; for (let doc of docs) { await db.post (DOC); }}
If you do want multiple requests to execute concurrently, you can use the Promise.all method.
4, the implementation of the Async function principle, is to Generator function and automatic actuator, wrapped in a function.
5.
function Loginorder (URLs) { // concurrent read remote URL Const textpromises = urls.map (async URL + = { = await fetch (URL); return Response.text (); }); // output by order for (const textpromise of textpromises) { console.log (await textpromise);} }
In the above code, although map the parameter of the method is a async function, it is executed concurrently, because only the inside of the async function is secondary execution, the outside is unaffected. The back for..of loop is used internally await , so the output is implemented sequentially.
JS-ES6 Learning notes-async function (3)