Promise is not working in azure function app javascript

假如想象 提交于 2020-03-05 04:59:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!