javascript - ES2015 equivalent of $.Deferred() -


i'm using babel project , i'm stuck basic problem. i'm used jquery's deferred objects , i'm struggling find es2015 equivalent, here want:

// file1.js let dfd = new promise()  function functioncalledatsomepoint(thing) {     dfd.resolve(thing) }  export default { dfd }   // file2.js import { dfd } './file1'  dfd.then((thing) => {     console.log('yay thing:', thing) }) 

what should correct way right simple deferred?

edit royhowie's answer:

// file1.js let thing function getthing(_thing) {     return new promise((resolve) => {         if (el) {             thing = new thing(el)         }         resolve(thing)     }) }  function functioncalledatsomepoint(el) {     getthing(el) }  export default { getthing }   // file2.js import { getthing } './file1'  getthing.then((thing) => {     console.log('yay thing:', thing) }) 

you can export promise directly (instead of function)—like have—but you'll able use (.then) once, not want.

instead, should export function returns promise:

file 1.js

import user '../models/user'  export function getusersfromdatabase () {     return new promise((resolve, reject) => {         user.find({}, (err, users) => {             return err ? reject(err) : resolve(users)         })     }) } 

file2.js

import { getusersfromdatabase } './file1'  getusersfromdatabase().then((users) => {     // success }).catch((err) => {     // no users }) 

you can use default promise implementation, but slower 3rd party modules, e.g., bluebird (which recommend using).


Comments

Popular posts from this blog

how to do line continuation in perl debugger for entering raw multi-line text (EOT)? -

javascript - Create websocket without connecting -

sharepoint - Accessing files across a shared directory using a Windows service -