es6-promise

Does JavaScript promise create memory leaks when not rejected or resolved?

こ雲淡風輕ζ 提交于 2019-12-05 06:23:10
I'm in a situation where I need execute async functions in "parallel", and continue program execution with the best result. Thus I wrote something like this : var p = []; for (var i = 0; i < 10; ++i) (function (index) { p.push(new Promise(function (resolve, reject) { setTimeout(function () { var success = Math.random() > 0.7; console.log("Resolving", index, "as", success ? "success" : "failure"); success && resolve(index); }, Math.random() * 5000 + 200); })); })(i); Promise.race(p).then(function (res) { console.log("FOUND", res); }).catch(function (err) { console.log("ERROR", err); }); Now, I

Whats the purpose of typescript's __awaiter

孤人 提交于 2019-12-05 04:56:39
consider this simple class class Test { private foo(): Promise<void> { return new Promise<void>((resolve, reject) => { resolve(); }); } private async bar() { await this.foo(); } } This get compiled into var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) :

What determines the call order of deferred function using promises or setTimeout?

99封情书 提交于 2019-12-05 04:22:54
Deferring the execution of functions, for example in custom event handling, is a common pattern in JavaScript (see, for example here ). It used to be that using setTimeout(myFunc,0) was the only way to do this, however with promises there is now an alternative: Promise.resolve().then(myFunc) . I had assumed that these would pretty much do the same thing, but while working on a library which included custom events I thought I'd find out if there was a difference, so I dropped the following block into node: var logfn=function(v){return function(){console.log(v)}}; setTimeout(logfn(1),0); Promise

Should synchronous code called by Promise .then create a new Promise

不问归期 提交于 2019-12-05 03:34:23
I've implemented some code, where asynchronous code is followed by some synchronous functions. For example: function processSomeAsyncData() { asyncFuncCall() .then(syncFunction) .catch(error); } If I understand correctly then is also a Promise. Then, should I create a promise in the synchronous code as well? function syncFunction() { const p = new Promise (function (resolve, reject) { //Do some sync stuff ... resolve(data); } return p; } If that isn't necessary, how do you reject the promise from the synchronous code if an error occurred? You don't need to create a new promise explicitly.

Javascript Recursive Promise

南楼画角 提交于 2019-12-05 03:21:53
I'm trying to create a recursive function using Promises, but can't quite seem to get it right. I have working code without using promises, but it uses counters and global variables etc. and doesn't feel quite right, so I'm attempting a rewrite and also creating a module for reuse. Essentially, the function is supposed to be getting a user from Active Directory and then recursively finding any direct reports and their direct reports and so on. I've played with lots of versions of the function, this is the current one: function loadReports(personEmail, list) { return new Promise((resolve,

Typescript returning boolean after promise resolved

情到浓时终转凉″ 提交于 2019-12-05 03:16:24
I'm trying to return a boolean after a promise resolves but typescript gives an error saying A 'get' accessor must return a value. my code looks like. get tokenValid(): boolean { // Check if current time is past access token's expiration this.storage.get('expires_at').then((expiresAt) => { return Date.now() < expiresAt; }).catch((err) => { return false }); } This code is for Ionic 3 Application and the storage is Ionic Storage instance. You can return a Promise that resolves to a boolean like this: get tokenValid(): Promise<boolean> { // | // |----- Note this additional return statement. // v

When should I call Promise.resolve() directly?

随声附和 提交于 2019-12-05 03:06:01
I've seen that the native ES6 Promise.resolve() can be invoked directly - as a static method. Facebook is using it that way in their Flux examples. But in what case should I do that? To queue something? Or instead of using window.setTimeout() ? Sergey Rybalkin You should call Promise.resolve(object) when you need to create a promise that is already resolved. For example you may have a function that starts downloading a resource from the server or returns its cached version: function getImage(imageUrl) { if (imageUrl in this.cache) { // no need to download, return immediately return Promise

TypeScript type definition for promise.reject

送分小仙女□ 提交于 2019-12-05 00:08:59
The following code is correct in terms of the type that is returned, because then always return the promise array. Promise.resolve(['one', 'two']) .then( arr => { if( arr.indexOf('three') === -1 ) return Promise.reject( new Error('Where is three?') ); return Promise.resolve(arr); }) .catch( err => { console.log(err); // Error: where is three? }) TypeScript throw error: The type argument for type parameter 'TResult' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'void' is not a valid type argument because it is not a supertype of

How to use jQuery's $.post() method with async/await and typescript

百般思念 提交于 2019-12-04 23:45:28
My await statements inside the async functions are calls to jQuery's $.post() method which return a valid promise, however I am getting this error in TypeScript: Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member. My function is this (simplified for the example). The code is valid and works, but I am getting a error in the TS console. async function doAsyncPost() { const postUrl = 'some/url/'; const postData = {name: 'foo', value: 'bar'}; let postResult; let upateResult; function failed(message: string, body?: string) { console.log('error: ',

How to get custom server-side error message with ecmascript-6 and fetch api?

烈酒焚心 提交于 2019-12-04 22:17:32
When a client-side fetch request results in an error on the server side, I'd like to return an error code (400) and a custom message. I don't know how to retrieve both on the client-side elegantly using fetch and promises. return fetch('/api/something') .then(response => response.json()) .then(json => { console.log(json.message) // I only have access to the json here. // I'd also like to get the response status code // (from the response object) and potentially // throw an error complete with the custom message. }) .catch(function(ex) { console.log('Unhandled Error! ', ex); }); Thanks! You