-2

In the following javascript code snippet (written for nodejs), the createDoc function returns a promise. Upon fulfillment of the promise, the handler passed to .then is invoked. The question is that how can I make .then return doc? According to the documentation, .then returns a promise but I'm really looking for it to return doc.

 let p = createDoc(title).then(function (doc) {return doc;});

 //p is a promise, and not doc
 console.log(p);

What is the proper way to access the value passed to the fulfillment handler (doc in this case) outside the .then?

katboo
  • 55
  • 7

2 Answers2

1

do something like this and when the promise resolves the value of doc will be inside p

let p;
createDoc(title).then(doc => p = doc);
arnavpanwar99
  • 377
  • 2
  • 6
0

You can use async-await, if you want to have the value instead of promise in p

async function someFunction() {
    ...
    let p = await createDoc(title);
     console.log(p);

    ...
}

What you are seeing is a behavior of promises calling chaining.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400