1

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!

Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113

2 Answers2

3

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");
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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);

};
Piotr Szlagura
  • 650
  • 5
  • 15