npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ask-for-promise

v2.0.3

Published

promise utility library

Downloads

25

Readme


Ask for Promise

version license npm GitHub issues GitHub top language GitHub code size in bytes npm bundle size

Decouple promises from their 'resolve' and 'reject' functions and make posible to use them with any javascript function ( sync or async). 'Ask-for-promise' also provide sugar syntax for some long statements.

'Ask-for-promise' provides also an option to set a ttl ( time to live) for the promise. If time is up promise will close with timeout message.


// standard promise pattern
let standardTask = new Promire ( (resolve,reject) => {
       // ... wrap everything related to the promise inside this function
       // when promise resolve - call resolve (result)
       // or call reject ( result )
    })

// after promise:
standardTask.then ( item => {
  // where 'item' is a 'result' argument sent from 'resolve' or 'reject' function. 
})



// askForPromise pattern
let askTask = askForPromise()
/* 
  askTask is an object that contains
  {
     promise    - Promise itself
     done       - function : Resolve function
     cancel     - function : Reject function
     onComplete - function : Sugar synax for askTask.promise.then
     timeout    - function : Set time to live for the promise
  }

  You can complete the promise anywhere in your code by writing:
  askTask.done(result)

  Or reject promise by:
  askTask.cancel(result)
*/

// after promise:
askTask.onComplete ( item => { 
// where 'item' is a 'result' argument sent from 'done' or 'cancel' function. 
})


// Execute a list of promise functions in sequence
let task = askForPromise.sequence ( [ function1, function2, function3 ] )
// where function1, function2, function3 are functions that return a promise
// function1 will be executed first, then function2 and function3
task.onComplete ( result => {
            // result is an array of results from all promises
   })


// Execute a list of promise functions in parallel
let task = askForPromise.all ( [ function1, function2, function3 ] )
// where function1, function2, function3 are functions that return a promise
// function1, function2 and function3 will be executed in parallel
task.onComplete ( result => {
            // result is an array of results from all promises in same order as they are in the array
   })

Installation

Install by writing in your terminal:

npm install ask-for-promise

Once it has been installed, it can be used by writing this line of JavaScript:

import askForPromise from 'ask-for-promise'

Examples

Simple promise

let task = askForPromise()

asyncFunction ( someArgument, ( err, r ) => task.done ( 'task complete' )   )

task.onComplete ( r => console.log(r)   )

// Method 'onComplete' is sugar syntax for 'task.promise.then'.
// task.promise.then ( r => { console.log ( r ) })

AskForPromise will return an object. Property task.promise will contain promise it self. Resolve function is available as task.done and reject function as task.cancel. Completion of asyncFunction will complete the promise with 'task complete' argument and will print a console message 'task complete'.

Let's do a Promise.race without using Promise.race.

let task = askForPromise()

async_1 ( arg, ( err, r) => task.done('1') )
async_2 ( arg, ( err, r) => task.done('2') )

task.onComplete ( r => console.log(r)   )
// It's equal of:
// task.promise.than ( r => console.log ( r )   )

It's almost the same as previous example - right?

Long Promise Chain

Let's see how looks long chain of promises:


// Keep definition of all promises together.
let prepareFolders  = askForPromise()
let writeFiles      = askForPromise()
let updateInterface = askForPromise()

// myFS is a dummy library that works with files.
myFS.makeFolders ( folders, ( err , r ) => prepareFolders.done() )

prepareFolders
 .onComplete ( () => {
                  myFS.writeFiles ( files , () => writeFiles.done() )
                  return writeFiles.promise
              })
.then ( () => {
                 updateInterface ()  // if it's not async.
                 updateInterface.done()
                 return updateInterface.promise
   })
.then ( () => {
                 console.log('DONE')
   })

Promise with Timeout

let final;
const task = askForPromise().timeout ( 2000, 'expire' );
// setTimeout: .timeout ( ttl, 'expireMessage'). ttl is time to live in milliseconds

task.onComplete ( result => {
    if ( result === 'expire' ) final = 'timeout'                    // ... it's after timeout
    else                       final = 'success resolved promise'
})

Promise All

Promise all by providing array of data. Here is the example:


  const files = [ 'info.txt', 'general.txt', 'about.txt' ]

  let writeFile = askForPromise ( files )

  files.forEach ( (file,i) => {
          fs.writeFile ( file,'dummy text', () => writeFile[i].done() )
       })

writeFile.onComplete ( () => console.log ( 'DONE' )   )
  

/*
Last statement is equivalent of:
Promise
   .all ( writeFile.promises )
   .then ( () => console.log ( 'DONE' )   )
*/

When function askForPromise get argument will return array of askForPromises object and property 'promises' will contain array of all promises.

Control of single promise and many promises

With 'ask-for-promise' asking for one or many promises have almost same syntax. There is some code sample to illustrate this:


  // ask for single promise
     let singlePromise = askForPromise ()

 // ask for list of promises
    let listOfItems = [ 'first', 'second', 'third' ]
    let manyPromises = askForPromise ( listOfItems )

 /* 
     manyPromises statement is short version of this:
     let temp  = listOfItems.map ( item => askForPromise ()   )
     let manyPromises = temp.map ( o => o.promise )
 */


 // Promise complete for single promise
    singlePromise.onComplete ( (r) => { console.log (r)   })

 // All promises for the array are completed.
    manyPromises.onComplete ( (r) => { console.log (r)   })

More

For more examples please visit "test" folder of the project.

External Links

Credits

'ask-for-promise' was created by Peter Naydenov.

License

'ask-for-promise' is released under the MIT License.