Q:

javascript return promise

function doSomething() {
  return new Promise((resolve, reject) => {
    console.log("It is done.");
    // Succeed half of the time.
    if (Math.random() > .5) {
      resolve("SUCCESS")
    } else {
      reject("FAILURE")
    }
  })
}

const promise = doSomething(); 
promise.then(successCallback, failureCallback);
1
var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);
29
const p1 = new Promise((resolve, reject) => {
    console.log("Promise has started");
    const lifeIsEasy = false;
    if (lifeIsEasy) {
        //Value to be returned if the promise is resolved
        //return value is optional
        resolve("No it's not");
    }
    else {
        //Value to be returned if the promise is rejected
        //return value is also optional
        reject("welcome to the real world");
    }
});
//then is executed when the promise is resolved
p1.then(value => {
    console.log(value);
})
//catch is executed when the promise is rejected
  .catch (err => {
    console.log(err);
});

/*expected output
Promise has started
welcome to the real world*/
14
function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}
0
const myFirstPromise = new Promise((resolve, reject) => {
  // esegue qualcosa di asincrono che eventualmente chiama:
  //
     resolve(someValue); // fulfilled
  // oppure
     reject("motivo del fallimento"); // rejected
});
-1

New to Communities?

Join the community