Questions tagged [promise]
Promises are a tactic for deferred computing, suitable for several styles of concurrency: thread and event loop concurrency for local computation, and both synchronous and asynchronous remote messaging. A promise represents the eventual result of an asynchronous operation. The primary way of working with promises is through a method which registers transformations from the promise's eventual value or failure reason to a new promise.
                                	
	promise
    
                            
                        
                    
            22,671
            questions
        
        
            3147
            votes
        
        
            34
            answers
        
        
            2.2m
            views
        
    Using async/await with a forEach loop
                Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.
import fs from 'fs-promise'
async function ...
            
        
       
    
            1875
            votes
        
        
            35
            answers
        
        
            829k
            views
        
    What is the difference between Promises and Observables?
                What is the difference between Promise and Observable in Angular?
An example on each would be helpful in understanding both the cases. In what scenario can we use each case?
            
        
       
    
            928
            votes
        
        
            11
            answers
        
        
            688k
            views
        
    Syntax for an async arrow function
                I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this:
async function foo() {
  // Do something
}
What is the equivalent syntax for arrow ...
            
        
       
    
            870
            votes
        
        
            24
            answers
        
        
            326k
            views
        
    How do I convert an existing callback API to promises?
                I want to work with promises but I have a callback API in a format like:
1. DOM load or other one time event:
window.onload; // set to callback
...
window.onload = function() {
};
2. Plain ...
            
        
       
    
            754
            votes
        
        
            17
            answers
        
        
            257k
            views
        
    How do I access previous promise results in a .then() chain?
                I have restructured my code to promises, and built a wonderful long flat promise chain, consisting of multiple .then() callbacks. In the end I want to return some composite value, and need to access ...
            
        
       
    
            654
            votes
        
        
            8
            answers
        
        
            375k
            views
        
    JavaScript Promises - reject vs. throw
                I have read several articles on this subject, but it is still not clear to me if there is a difference between Promise.reject vs. throwing an error. For example,
Using Promise.reject
return ...
            
        
       
    
            652
            votes
        
        
            3
            answers
        
        
            140k
            views
        
    What is the explicit promise construction antipattern and how do I avoid it?
                I was writing code that does something that looks like:
function getStuffDone(param) {
    return new Promise(function(resolve, reject) {
        myPromiseFn(param+1)  
        .then(function(val) { 
 ...
            
        
       
    
            584
            votes
        
        
            20
            answers
        
        
            284k
            views
        
    Wait until all promises complete even if some rejected
                Let's say I have a set of Promises that are making network requests, of which one will fail:
// http://does-not-exist will throw a TypeError
var arr = [ fetch('index.html'), fetch('http://does-not-...
            
        
       
    
            549
            votes
        
        
            10
            answers
        
        
            543k
            views
        
    Use async await with Array.map
                Given the following code:
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
        await callAsynchronousOperation(item);
        return item +...
            
        
       
    
            524
            votes
        
        
            12
            answers
        
        
            332k
            views
        
    jQuery deferreds and promises - .then() vs .done()
                I've been reading about jQuery deferreds and promises and I can't see the difference between using .then() & .done() for successful callbacks. I know Eric Hynds mentions that .done() and .success()...
            
        
       
    
            521
            votes
        
        
            29
            answers
        
        
            177k
            views
        
    Resolve Javascript Promise outside the Promise constructor scope
                I have been using ES6 Promise.
Ordinarily, a Promise is constructed and used like this
new Promise(function(resolve, reject){
    if (someCondition){
        resolve();
    } else {
        reject();...
            
        
       
    
            519
            votes
        
        
            19
            answers
        
        
            273k
            views
        
    How to check if an object is a Promise?
                Whether it's an ES6 Promise or a Bluebird Promise, Q Promise, etc.
How do I test to see if a given object is a Promise?
            
        
       
    
            508
            votes
        
        
            10
            answers
        
        
            129k
            views
        
    Aren't promises just callbacks?
                I've been developing JavaScript for a few years and I don't understand the fuss about promises at all.
It seems like all I do is change:
api(function(result){
    api2(function(result2){
        ...
            
        
       
    
            456
            votes
        
        
            9
            answers
        
        
            127k
            views
        
    What is std::promise?
                I'm fairly familiar with C++11's std::thread, std::async and std::future components (e.g. see this answer), which are straight-forward.
However, I cannot quite grasp what std::promise is, what it does ...
            
        
       
    
            426
            votes
        
        
            36
            answers
        
        
            360k
            views
        
    Resolve promises one after another (i.e. in sequence)?
                Consider the following code that reads an array of files in a serial/sequential manner. readFiles returns a promise, which is resolved only once all files have been read in sequence.
var readFile = ...
            
        
       
    
            415
            votes
        
        
            6
            answers
        
        
            142k
            views
        
    Do I need to return after early resolve/reject?
                Suppose I have the following code.
function divide(numerator, denominator) {
 return new Promise((resolve, reject) => {
  if(denominator === 0){
   reject("Cannot divide by 0");
   return; //...
            
        
       
    
            401
            votes
        
        
            6
            answers
        
        
            307k
            views
        
    What's the difference between returning value or Promise.resolve from then()
                What is the difference between:
new Promise(function(res, rej) {
    res("aaa");
  })
  .then(function(result) {
    return "bbb"; // directly returning string
  })
  .then(function(result) {
    ...
            
        
       
    
            383
            votes
        
        
            9
            answers
        
        
            225k
            views
        
    What's the difference between a Future and a Promise?
                What's the difference between Future and Promise?
They both act like a placeholder for future results, but where is the main difference?
            
        
       
    
            337
            votes
        
        
            15
            answers
        
        
            845k
            views
        
    Axios handling errors
                I'm trying to understand javascript promises better with Axios. What I pretend is to handle all errors in Request.js and only call the request function from anywhere without having to use catch().
In ...
            
        
       
    
            323
            votes
        
        
            5
            answers
        
        
            118k
            views
        
    What are the differences between Deferred, Promise and Future in JavaScript?
                What are the differences between Deferreds, Promises and Futures?
Is there a generally approved theory behind all these three?
            
        
       
    
            312
            votes
        
        
            3
            answers
        
        
            156k
            views
        
    Promise.all: Order of resolved values
                Looking at MDN it looks like the values passed to the then() callback of Promise.all contains the values in the order of the promises. For example:
var somePromises = [1, 2, 3, 4, 5].map(Promise....
            
        
       
    
            309
            votes
        
        
            14
            answers
        
        
            196k
            views
        
    Is Node.js native Promise.all processing in parallel or sequentially?
                I would like to clarify this point, as the documentation is not too clear about it;
Q1: Is Promise.all(iterable) processing all promises sequentially or in parallel? Or, more specifically, is it the ...
            
        
       
    
            283
            votes
        
        
            9
            answers
        
        
            650k
            views
        
    Why is my asynchronous function returning Promise { <pending> } instead of a value?
                My code:
let AuthUser = data => {
  return google.login(data.username, data.password).then(token => { return token } )
}
And when i try to run something like this:
let userToken = AuthUser(...
            
        
       
    
            279
            votes
        
        
            14
            answers
        
        
            718k
            views
        
    How can I access the value of a promise?
                I'm looking at this example from Angular's documentation for $q, but I think this probably applies to promises in general. The example below is copied verbatim from their documentation with their ...
            
        
       
    
            262
            votes
        
        
            6
            answers
        
        
            109k
            views
        
    Difference between microtask and macrotask within an event loop context
                I've just finished reading the Promises/A+ specification and stumbled upon the terms microtask and macrotask: see http://promisesaplus.com/#notes
I've never heard of these terms before, and now I'm ...
            
        
       
    
            259
            votes
        
        
            31
            answers
        
        
            157k
            views
        
    How can I synchronously determine a JavaScript Promise's state?
                I have a pure JavaScript Promise (built-in implementation or poly-fill):
var promise = new Promise(function (resolve, reject) { /* ... */ });
From the specification, a Promise can be one of:
'...
            
        
       
    
            253
            votes
        
        
            1
            answer
        
        
            71k
            views
        
    Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises? [closed]
                After Node.js added native support for promises, are there still reasons to use libraries like Q or BlueBird? 
For example if you are starting a new project and let's assume in this project you don't ...
            
        
       
    
            242
            votes
        
        
            6
            answers
        
        
            191k
            views
        
    Why does .json() return a promise, but not when it passes through .then()?
                I've been messing around with the fetch() api recently, and noticed something which was a bit quirky. 
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
  ...
            
        
       
    
            240
            votes
        
        
            8
            answers
        
        
            100k
            views
        
    How to unwrap the type of a Promise?
                Say I have the following code:
async promiseOne() {
  return 1
} // => Promise<number>
const promisedOne = promiseOne()
typeof promisedOne // => Promised<number>
How would I go ...
            
        
       
    
            238
            votes
        
        
            7
            answers
        
        
            37k
            views
        
    When is .then(success, fail) considered an antipattern for promises?
                I had a look at the bluebird promise FAQ, in which it mentions that .then(success, fail) is an antipattern. I don't quite understand its explanation as for the try and catch.
What's wrong with the ...
            
        
       
    
            234
            votes
        
        
            8
            answers
        
        
            383k
            views
        
    Return from a promise then()
                I have got a javascript code like this:
function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}
var test = justTesting();
I have got always an undefined value for ...
            
        
       
    
            233
            votes
        
        
            6
            answers
        
        
            122k
            views
        
    How do I promisify native XHR?
                I want to use (native) promises in my frontend app to perform XHR request but without all the tomfoolery of a massive framework.
I want my xhr to return a promise but this doesn't work (giving me: ...
            
        
       
    
            233
            votes
        
        
            5
            answers
        
        
            94k
            views
        
    How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?
                Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often: 
(node:11057) UnhandledPromiseRejectionWarning: Unhandled ...
            
        
       
    
            220
            votes
        
        
            5
            answers
        
        
            530k
            views
        
    How do I wait for a promise to finish before returning the variable of a function?
                I'm still struggling with promises, but making some progress thanks to the community here.
I have a simple JS function which queries a Parse database. It's supposed to return the array of results, ...
            
        
       
    
            197
            votes
        
        
            5
            answers
        
        
            69k
            views
        
    Is it bad practice to have a constructor function return a Promise?
                I'm trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing them, sending them through ...
            
        
       
    
            196
            votes
        
        
            8
            answers
        
        
            212k
            views
        
    How to pass parameter to a promise function
                this might seem a silly question but I am a newbie in this topic. I am working on promises on node js. And I want to pass parameter to a promise function. However I could not figure it out.
...
            
        
       
    
            196
            votes
        
        
            8
            answers
        
        
            131k
            views
        
    How to cancel an $http request in AngularJS?
                Given a Ajax request in AngularJS
$http.get("/backend/").success(callback);
what is the most effective way to cancel that request if another request is launched (same backend, different parameters ...
            
        
       
    
            189
            votes
        
        
            8
            answers
        
        
            290k
            views
        
    Using setTimeout on promise chain
                Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next ...
            
        
       
    
            185
            votes
        
        
            5
            answers
        
        
            461k
            views
        
    How to wait for a JavaScript Promise to resolve before resuming function?
                I'm doing some unit testing. The test framework loads a page into an iFrame and then runs assertions against that page.  Before each test begins, I create a Promise which sets the iFrame's onload ...
            
        
       
    
            181
            votes
        
        
            10
            answers
        
        
            174k
            views
        
    How to promisify Node's child_process.exec and child_process.execFile functions with Bluebird?
                I'm using the Bluebird promise library under Node.js, it's great! But I have a question:
If you take a look at the documentation of Node's child_process.exec and child_process.execFile you can see ...
            
        
       
    
            181
            votes
        
        
            13
            answers
        
        
            147k
            views
        
    Promise - is it possible to force cancel a promise
                I use ES6 Promises to manage all of my network data retrieval and there are some situations where I need to force cancel them.
Basically the scenario is such that I have a type-ahead search on the UI ...
            
        
       
    
            179
            votes
        
        
            6
            answers
        
        
            116k
            views
        
    Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments
                According to AngularJS doc, calls to $http return the following:
  Returns a promise object with the standard then method and two http specific methods: success and error. The then method takes two ...
            
        
       
    
            179
            votes
        
        
            3
            answers
        
        
            64k
            views
        
    Placement of catch BEFORE and AFTER then
                I have trouble understanding the difference between putting .catch BEFORE and AFTER then in a nested promise.
Alternative 1:
test1Async(10).then((res) => {
  return test2Async(22)
    .then((res) ...
            
        
       
    
            177
            votes
        
        
            23
            answers
        
        
            189k
            views
        
    typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here
                I am trying to use Typescript for my AWS Lambda and i am getting the following errors where ever I use promises.
error TS2693: 'Promise' only refers to a type, but is being used as a value here.
I ...
            
        
       
    
            174
            votes
        
        
            4
            answers
        
        
            122k
            views
        
    How do I properly test promises with mocha and chai?
                The following test is behaving oddly:
it('Should return the exchange rates for btc_ltc', function(done) {
    var pair = 'btc_ltc';
    shapeshift.getRate(pair)
        .then(function(data){
        ...
            
        
       
    
            173
            votes
        
        
            6
            answers
        
        
            200k
            views
        
    How to create an Observable from static data similar to http one in Angular?
                I am having a service that has this method:
export class TestModelService {
    public testModel: TestModel;
    constructor( @Inject(Http) public http: Http) {
    }
    public fetchModel(uuid: ...
            
        
       
    
            172
            votes
        
        
            5
            answers
        
        
            170k
            views
        
    Returning Promises from Vuex actions
                I recently started migrating things from jQ to a more structured framework being VueJS, and I love it!
Conceptually, Vuex has been a bit of a paradigm shift for me, but I'm confident I know what its ...
            
        
       
    
            169
            votes
        
        
            8
            answers
        
        
            542k
            views
        
    Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai
                So, I'm testing a component that relies on an event-emitter. To do so I came up with a solution using Promises with Mocha+Chai:
it('should transition with the correct event', (done) => {
  const ...
            
        
       
    
            168
            votes
        
        
            5
            answers
        
        
            370k
            views
        
    How to use fetch in TypeScript
                I am using window.fetch in Typescript, but I cannot cast the response directly to my custom type:
I am hacking my way around this by casting the Promise result to an intermediate 'any' variable. 
...
            
        
       
    
            167
            votes
        
        
            11
            answers
        
        
            139k
            views
        
    JavaScript array .reduce with async/await
                Seem to be having some issues incorporating async/await with .reduce(), like so:
const data = await bodies.reduce(async(accum, current, index) => {
  const methodName = methods[index]
  const ...