问题
I have simple demo to understand Promise concept but it is not working as expected, see my code which i have tried.
module.exports = async function (context, iotHubMessage) {
context.log('START');
var promise1 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('foo');
}, 1000);
});
context.log(promise1);
promise1.then(function (resolve) {
context.log(resolve);
// expected output: "foo"
});
};
and I am geting this output
2019-01-24T12:58:38.695 [Information] START
2019-01-24T12:58:38.695 [Information] Promise { <pending> }
2019-01-24T12:58:38.696 [Information] Executed
why am not getting foo at output log please help me thanks!
回答1:
It seems that Azure is killing your process after the function has returned. Because it didn't return a promise (or rather, didn't return a promise that did wait for your timeout), it did not wait for the promise callback to run.
You can use
module.exports = function(context, iotHubMessage) {
// ^^^^^^^^ no async necessary here
context.log('START');
var promise1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 1000);
});
context.log(promise1);
var promise2 = promise1.then(function() {
context.log("promise fulfilled");
});
return promise2;
// ^^^^^^^^^^^^^^^^
}
or with async/await syntax:
module.exports = async function(context, iotHubMessage) {
context.log('START');
var promise1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 1000);
});
context.log(promise1);
await promise1;
// ^^^^^
context.log("promise fulfilled");
}
回答2:
Maybe instead of promise1.then(...) try:
module.exports = async function (context, iotHubMessage) {
context.log('START');
var promise1 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('foo');
}, 1000);
});
context.log(promise1);
// Use await instead of promise.then(...)
let resolve = await promise1;
context.log(resolve);
};
来源:https://stackoverflow.com/questions/54347873/promise-is-not-working-in-azure-function-app-javascript