问题描述
我的示例代码:
let name;
Login.findOne().then(() => {
name = 'sameer';
}); // consider this is async code
console.log(name);
因此上述代码异步工作,因此现在我的console.log变得未定义.
So the above code works async, so now my console.log became undefined.
我使用回调使代码像同步一样工作.
I used callbacks to make the code work like synchronous.
我的回调代码:
let name;
const callback = () => {
console.log(name);
};
Login.findOne().then(() => {
name = 'sameer';
callback();
});
现在可以正常工作了,
我的问题是如何用promise和async await代替回调来代替这段小代码?
My question is how you replace this small code with promises and async await instead of callbacks?
推荐答案
await
让您以某种同步的方式编写异步代码:
await
lets you write asynchronous code in a somewhat synchronous fashion:
async function doIt() {
let name = await Login.findOne();
console.log(name);
// You can use the result here
// Or, if you return it, then it becomes the resolved value
// of the promise that this async tagged function returns
return name;
}
// so you can use `.then()` to get that resolved value here
doIt().then(name => {
// result here
}).catch(err => {
console.log(err);
});
简单的承诺版本就是这样:
The plain promises version would be this:
function doIt() {
// make the query, return the promise
return Login.findOne();
}
// so you can use `.then()` to get that resolved value here
doIt().then(name => {
// result here
}).catch(err => {
console.log(err);
});
请记住,await
只能在async
函数内部使用,迟早要使用它,您仍然经常必须使用.then()
来查看何时完成所有操作.但是,很多时候,使用await
可以简化顺序异步操作.
Keep in mind that await
can only be used inside an async
function so sooner or later, you often still have to use .then()
to see when everything is done. But, many times, using await
can simplify sequential asynchronous operations.
如果您有多个顺序的异步操作,则会有更多不同:
It makes a lot more difference if you have multiple, sequential asynchronous operations:
async function doIt() {
let result1 = await someFunc1();
let result2 = await someFunc2(result1 + 10);
return someFunc3(result2 * 100);
}
如果没有等待,这将是:
Without await, this would be:
function doIt() {
return someFunc1().then(result1 => {
return someFunc2(result1 + 10);
}).then(result2 => {
return someFunc3(result2 * 100);
});
}
添加更多用于处理中间结果或逻辑流分支的逻辑,如果没有await
,它将变得越来越复杂.
Add in more logic for processing the intermediate results or branching of the logic flow and it gets more and more complicated without await
.
有关更多示例,请参见如何链接并与Promises 共享以前的结果,以及await
版本要简单多少.
For more examples, see How to chain and share prior results with Promises and how much simpler the await
version is.
这篇关于Node.js中的承诺和异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!