2

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!

4
  • That code will definitely eventually run that console.log(resolve) with 'foo' if the process is still running a second later. Did you look later in the output? Commented Jan 24, 2019 at 13:35
  • 1
    Note that there's no reason to mark that function async. It doesn't ever use await. Commented Jan 24, 2019 at 13:35
  • can you post the code of context.log function? Commented Jan 24, 2019 at 13:36
  • yes @T.J.Crowder i waited before copy log Commented Jan 24, 2019 at 14:06

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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

};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.