0

I am relatively new to javascript and have decided to write a promise api myself. The function takes promises as a parameter and returns the last one resolved. Instead of deleting resolved promises in multiplies them in a strange way. Please help if you can.

function remove(array,index){
    return array.slice(0,index).concat(array.slice(index+1));
}

Promise.last=function(arr){
    let leng=arr.length;
    
    for(let i=1;i<leng;i++){
        console.log("loop");
        Promise.race(arr)
        .then((res)=>{
            
            arr=remove(arr,arr.indexOf(res));
        }      
        );
    }
    return arr;
}
const promise1 = new Promise((resolve,reject)=>
    setTimeout(resolve, 100 , "firstpromise"));
const promise2 = new Promise((resolve,reject)=>
    setTimeout(resolve, 2000 , 'secondpromise'));
const promise3 = new Promise((resolve,reject)=>
    setTimeout(resolve, 3000 , 'thirdpromise'));


console.log(Promise.last([promise1,promise2,promise3,22]));

This is what it outputs in the console: [Promise, Promise, Promise,22]

Alexey_js
  • 77
  • 5
  • 1
    Your `last` method will need to return a promise for its result. Currently it immediately returns the array that it received as the argument. – Bergi Apr 29 '20 at 12:34
  • 3
    "*This is what it outputs in the console*" - no, it doesn't. The code you posted logs `[Promise, Promise, Promise, 22]`. – Bergi Apr 29 '20 at 12:35
  • 2
    You're returning `arr` before the promises have (asyncronously) resolved. – Quentin Apr 29 '20 at 12:38
  • 1
    Logs `[ {}, {}, {}, 22 ]` for me... – Jeremy Thille Apr 29 '20 at 12:39
  • What I aimed was to leave in the array the promise that will be resolved last – Alexey_js Apr 29 '20 at 12:42
  • 1
    I think you should make an Observable of Promises, it could simply return the last resolved while avoiding race conditions... Observables are quite complex to master, but super powerful. Have a look at [RxJS](https://rxjs-dev.firebaseapp.com/guide/observable) – Jeremy Thille Apr 29 '20 at 12:42
  • 1
    Using .race() to remove a resolved promise - and then re-run race() to remove the next, until you are left with one. I believe that you will get an inconsistent result – Salmin Skenderovic Apr 29 '20 at 12:43
  • Maybe it has completed for loop before it resolved over 3 promises – Alexey_js Apr 29 '20 at 12:47
  • 1
    No. It completes the `for` loop, and _then_ the Promises get resolved. `for` is synchronous, Promises are asynchronous. Their completion takes time, and during this time, the thread doesn't stop (that's the whole point of asynchronism), so the `for` loop completes long before the first Promise gets resolved. – Jeremy Thille Apr 29 '20 at 12:59
  • 1
    @Alexey_js I don't think this topic should have been closed. Here is an alternative solution that returns the last resolved item: https://jsfiddle.net/2Lzakn5s/ – Salmin Skenderovic Apr 29 '20 at 13:04

0 Answers0