Jeongkuk Seo
Jeongkuk Seo

Reputation: 165

why promise.resolve lost value inside of async function?

I know when we use promise in JavaScript, we usally use two ways like below.

var f1 = () => {
  return new Promise( (resolve, reject) => {
    resolve(10);
  })
}

var f2 = () => {
  return Promise.resolve(10)
}

f1().then( data => { console.log(data) })  // 10
f2().then( data => { console.log(data) })  // 10

But if i use async function inside of promise, Promise.resolve lost the value like below.

const fs = require('fs')

var f1 = () => {
  return new Promise( (resolve, reject) => {
    fs.readFile('data.txt', (err, data) => {
      resolve(data);
    })
  })
}

var f2 = () => {
  return Promise.resolve()
  .then(() => {
    fs.readFile('data.txt', (err, data) => {
      //return data              --> undefined
      //Promise.resolve(data)    --> undefined
      return Promise.resolve()   --> undefined
    })
  })
}

f1().then( data => { console.log('1,',data) })
f2().then( data => { console.log('2,',data) })

I think that i use wrong way about Promise.resolve,,, OR Promise.resolve not support async function... someone tell me why Promose.resolve fail..

Upvotes: 0

Views: 211

Answers (1)

Bergi
Bergi

Reputation: 665100

If you have a value that you immediately want to resolve a promise with, you can use Promise.resolve().

If you get the value asynchronously in a callback, you must use the new Promise constructor with the resolve/reject callbacks, there is no way around it.

Upvotes: 2

Related Questions