22

I have lot of confusion in promise. It's a synchronous or asynchronous ?

return new Promise (function(resolved,reject){
    //sync or async? 
});
Duc Filan
  • 6,769
  • 3
  • 21
  • 26
udayakumar
  • 639
  • 1
  • 7
  • 16

7 Answers7

41

The function you pass into the Promise constructor runs synchronously, but anything that depends on its resolution will be called asynchronously. Even if the promise resolves immediately, any handlers will execute asynchronously (similar to when you setTimeout(fn, 0)) - the main thread runs to the end first.

This is true no matter your Javascript environment - no matter whether you're in Node or a browser.

console.log('start');
const myProm = new Promise(function(resolve, reject) {
  console.log('running');
  resolve();
});
myProm.then(() => console.log('resolved'));
console.log('end of main block');
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • But according to Mozilla site, that function you passed into is asynchronous. See the paragraph that starts with "Typically, it works like this: The operation within tetherFunction....". https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Aung Khant Mar 24 '20 at 10:45
  • 1
    It's referring to the usual way to [convert a callback API to a Promise](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises), in which case an asynchronous, callback-based function is called inside the `tetherFunction`, and when that callback runs, `resolve` is called. – CertainPerformance Mar 24 '20 at 10:48
  • Nice! You might want to put that in your answer cos that what confused many people. – Aung Khant Mar 24 '20 at 10:50
  • to be more accurate, the function you pass into Promise constructor runs immediately(synchronously) but code inside the function is run asynchronously. – CodeJonSnow Aug 08 '21 at 20:27
6

Promises aren't exactly synchronous or asynchronous in and of themselves. When you create a promise the callback you pass to it is immediately executed and no other code can run until that function yields. Consider the following example:

new Promise(function(resolve, reject) {
  console.log('foo');
})
console.log('bar');

The code outside the promise has to wait for the code inside the promise (which is synchronous) to complete before it can begin execution.

That said, promises are a common way of dealing with asynchronous code. The most common use case for a promise is to represent some value that's being generated or fetched in an asynchronous fashion. Logic that depends on that value can asynchronously wait until the value is available by registering a callback with .then() or related Promise methods.

Ryan Jenkins
  • 878
  • 8
  • 16
  • 1
    Synchronous means that code can only run after the previous task/line of code is complete. Async means that two piece of code can run in parallel. The code outside the promise *DOES NOT* have to wait for the code inside the promise to complete unless you are using the await syntax to wait for it, which converts async to sync. – Leo Lei Apr 20 '20 at 02:28
  • 1
    As you can see from the example though, the code outside the promise does, in fact, wait for the code inside of the promise to yield before executing. Promises are not inherently asynchronous, they're just a way of representing a value that may be generated by an asynchronous process. – Ryan Jenkins Apr 21 '20 at 03:59
  • sure, fair enough. I still find this statement hard to understand tho "Logic that depends on that value can asynchronously wait". I think that value is waited synchronously - that's exactly what sync means, the code cannot be executed before some other code is finished. – Leo Lei Apr 21 '20 at 06:00
5

This code makes it clearer:

        console.log("0");
        new Promise((resolve, reject) => {
          console.log("1");
          resolve();
        }).then(() => {
          console.log("2");
        });
        console.log("3");

The code prints: 0 1 3 2 So, then runs asynchronously while the main call back function runs synchronously.

Omar Diaa
  • 258
  • 4
  • 19
2

When you create a promise and pass a call back to it that callback is gonna executed immediately (sync)

const promise= new Promise(function(resolve, reject) {
      //doing some logic it gonna be executed synchronously
       console.log("result");
    })
    console.log("global log")
    

But when you resolve it by .then() method it will act in asynchronous way so for example :

const promise = new Promise(function(resolve, reject) {
  //doing some logic it gonna be executed synchronously

  resolve("fullfiled")
})
promise.then(v => {
  console.log(v)
})
console.log("global log")
Oday
  • 72
  • 4
2

I don't find other answers are accurate.

new Promise (executor_function)

executor_function here will run immediately as part of Promise initialization --- this means Promise init will be executed synchronously, but does not mean code inside executor_function will necessarily run synchronously, instead, code inside executor_function can also be run asynchronously, for example:

new Promise ((resolve, reject) => {
    setTimeout(resolve, 1000); // wait 1s 
})
CodeJonSnow
  • 114
  • 5
1

Promises are like normal classes in Javascript. Assume you are creating your own Promise implementation, your promise class would roughly look like this. Notice in your constructor you are expecting a method to be passed that you call immediately passing resolve and reject as parameters.

class Promise {
    constructor(method) {
        method(resolve, reject)
    }

    resolve() { ... }

    reject() { ... }

    then() { ... }
}

So when you do new Promise(), you are just creating a new object. Your Promise constructor will run, and it will call the method immediately. So that is why the code inside your promise gets executed synchronously.

return new Promise (function(resolved,reject){
    //sync or async? 
});

If inside your function you were calling another function that was async in nature, then that another function would get executed asynchronously, otherwise, everything else gets executed synchronously.

If you had chains in promise using then, then it only gets called after your first promise has called resolve().

return new Promise (function(resolve,reject){
  const a = 5*5; // sync operation.
  db.save(a, function callback() { // async operation.
    resolve() // tells promise to execute `then` block.
  });
});
Rash
  • 7,677
  • 1
  • 53
  • 74
0

const promise = new Promise(function(resolve, reject) {
  //doing some logic it gonna be executed synchronously
 console.log("check")
  resolve("fullfiled")
})
promise.then(v => {
  console.log(v)
})
console.log("global log")