我正在使用 async 和 await 来实现这一点。以下是我的代码,它按预期工作。
function publish() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("SUCCESS");
}, 3000);
});
}
var res;
async function sendRequest() {
console.log("START\n");
res = await publish();
console.log("RESULT: ",res)
console.log("END\n");
}
sendRequest();
输出如下:
START
SUCCESS
END
但我要实现的目标如下:
function publish() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("SUCCESS");
}, 3000);
});
}
var res;
async function sendRequest() {
console.log("START\n");
res = await publish();
console.log("RESULT: ",res)
console.log("END\n");
return res;
}
/**
* EXPECTED BEHAVIOUR
* Assume this function is an action of a controller class
* It will call sendRequest() and waits for its response.
* Once received, it will return that response to the client who called the action.
*/
function controller () {
return sendRequest();
}
/**
* ACTUAL BEHAVIOUR: It will out put following
* START
* FINAL RESPONSE Promise { <pending> }
* RESULT: SUCCESS
* SEND
*/
var endResult = controller ();
console.log("FINAL RESPONSE",endResult);
所以我的问题是为什么这个 FINAL RESPONSE Promise { <pending> }
在 RESULT: SUCCESS
之前打印.
- 如果这是
async
的行为await
,我怎样才能实现我的 预期的行为。我不想使用then()
在我的 Controller 中。 - 是否可以使用 while 循环?可能是我错了。这会很棒 如果有人可以指导我。
最佳答案
async..await
是 promises 的语法糖,提供类似同步的控制流。 async
函数只是一个始终返回 promise 的函数。每个 async
函数都可以重写为显式使用 Promise
并返回一个 promise 的常规函数。
I don't want to use then() in my controller.
那么controller
可以选择async
,调用它的函数应该是async
:
let endResult = await controller();
否则控制流会导致 this infamous problem .
Is it possible using while loop?
while
和其他循环语句支持async..await
。只要在async
函数内部执行循环,就是:
while (condition) {
let endResult = await controller();
// ...
}
为此,最好使用 async..await
,因为脱糖版本不那么吸引人,也更难理解:
let resultsPromise = Promise.resolve();
while (condition) {
resultsPromise = resultsPromise
.then(() => controller())
.then(endResult => {
// ...
});
}
resultsPromise.then(() => { /* loop has finished */ })
关于javascript - Javascript 中的异步阻塞请求 : Return value from async function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49425828/